package wykop.test.utils;

import java.util.concurrent.atomic.AtomicInteger;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.Node;

import wykop.page.WykopComment;
import wykop.page.WykopId;
import wykop.page.WykopPage;
import wykop.page.WykopUser;
import wykop.parser.ICommentParser;
import wykop.parser.NoCommentParsed;
import wykop.parser.UserProvider;

public class Utils {

	public static UserProvider fooUserProvider() {
		final AtomicInteger index = new AtomicInteger(1);

		return new UserProvider() {

			@Override
			public WykopUser getUserForName(String name) {
				WykopUser user = new WykopUser();
				user.setName(name);
				user.setId(index.incrementAndGet());
				return user;
			}
		};
	}

	public static ICommentParser fooCommentParser() {
		final AtomicInteger index = new AtomicInteger(1);

		return new ICommentParser() {

			@Override
			public WykopComment parseComment(Node node) throws NoCommentParsed {
				WykopComment comment = new WykopComment();
				comment.setId(index.incrementAndGet());
				return comment;
			}
		};
	}

    public static SessionFactory getSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
        	return new Configuration()
				.setProperty("hibernate.dialect",
						"org.hibernate.dialect.HSQLDialect")
				.setProperty("hibernate.connection.driver_class",
						"org.hsqldb.jdbcDriver")
				.setProperty("hibernate.connection.url",
						"jdbc:hsqldb:mem:baseball")
				.setProperty("hibernate.connection.username", "sa")
				.setProperty("hibernate.connection.password", "")
				.setProperty("hibernate.connection.pool_size", "1")
				.setProperty("hibernate.connection.autocommit", "true")
				.setProperty("hibernate.cache.provider_class",
						"org.hibernate.cache.HashtableCacheProvider")
				.setProperty("hibernate.current_session_context_class","thread")
				.setProperty("hibernate.hbm2ddl.auto", "create-drop")
				.setProperty("hibernate.show_sql", "false")
				.addClass(WykopComment.class)
				.addClass(WykopId.class)
				.addClass(WykopPage.class)
				.addClass(WykopUser.class)
				.buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
	
}
